type ProgressCallback = (progress: number) => void;

type ResourceType = 'image' | 'audio';

interface Resource {
  type: ResourceType;
  url: string;
}

function preloadImg(resource: Resource, done: () => void) {
  const img = new Image();
  img.src = resource.url;
  img.onload = function () {
    done();
  };
  img.onerror = function () {
    console.log('加载图片失败: ' + resource.url);
  };
}

function preloadAudio(resource: Resource, done: () => void) {
  const audio = new Audio();
  audio.src = resource.url;
  audio.onloadeddata = function () {
    done();
  };
  audio.onerror = function () {
    console.log('加载音频失败: ' + resource.url);
  };
  audio.load();
}

export default async function preloadResources(resourcePaths: string[], progressCallback?: ProgressCallback): Promise<void> {
    const resources: Resource[] = [];
    let doneCount = 0;

    function updateProgress() {
      doneCount = doneCount + 1;

      if (progressCallback) {
        progressCallback(doneCount / resources.length);
      }
    }

    for (const path of resourcePaths) {
        const type = path.endsWith('.mp3') ? 'audio' : 'image';
        resources.push({ type, url: path });
    }

    for (let i = 0; i < resources.length; i++) {
      if (resources[i].type === 'image') {
        preloadImg(resources[i], updateProgress);
      }

      if (resources[i].type === 'audio') {
        preloadAudio(resources[i], updateProgress);
      }
    }
}
